<template>
  <div class="admin-permissions">
    <div class="page-header">
      <h2>权限管理</h2>
      <div class="header-actions">
        <el-button 
          type="primary" 
          @click="showAddRoleDialog = true"
        >
          添加角色
        </el-button>
      </div>
    </div>
    
    <el-row :gutter="20">
      <!-- 角色列表 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>角色管理</span>
          </template>
          <div class="role-list">
            <div 
              v-for="role in rolesList" 
              :key="role.roleId"
              class="role-item"
              :class="{ active: selectedRole?.roleId === role.roleId }"
              @click="selectRole(role)"
            >
              <div class="role-info">
                <h4>{{ role.roleName }}</h4>
                <p>{{ role.remark }}</p>
                <div class="role-stats">
                  <span>角色编码: {{ role.roleCode }}</span>
                  <span>状态: {{ role.roleStatus === '00' ? '启用' : '禁用' }}</span>
                </div>
              </div>
              <div class="role-actions">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click.stop="editRole(role)"
                >
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click.stop="deleteRole(role)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 权限配置 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>权限配置</span>
          </template>
          <div v-if="selectedRole" class="permission-config">
            <h3>{{ selectedRole.roleName }} - 权限设置</h3>
            <el-form :model="permissionForm" label-width="100px">
              <el-form-item label="角色名称">
                <el-input v-model="permissionForm.name" />
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input v-model="permissionForm.description" type="textarea" />
              </el-form-item>
              <el-form-item label="权限设置">
                <div class="permission-groups">
                  <div v-for="group in permissionGroups" :key="group.key" class="permission-group">
                    <h4>{{ group.label }}</h4>
                    <el-checkbox-group v-model="permissionForm.permissions">
                      <el-checkbox 
                        v-for="permission in group.permissions" 
                        :key="permission.value"
                        :label="permission.value"
                      >
                        {{ permission.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="savePermissions" :loading="saving">
                  保存权限
                </el-button>
                <el-button @click="resetPermissions">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div v-else class="no-selection">
            <el-empty description="请选择一个角色进行权限配置" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="showAddRoleDialog"
      :title="editingRole ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input v-model="roleForm.code" :disabled="!!editingRole" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRole" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { systemApi } from '@/api/admin'

export default {
  name: 'AdminPermissions',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showAddRoleDialog = ref(false)
    const editingRole = ref(null)
    const selectedRole = ref(null)
    
    // 角色表单
    const roleForm = reactive({
      name: '',
      description: '',
      code: ''
    })
    
    // 权限表单
    const permissionForm = reactive({
      name: '',
      description: '',
      permissions: []
    })
    
    // 表单验证规则
    const roleRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入角色描述', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入角色标识', trigger: 'blur' },
        { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '角色标识只能包含字母、数字和下划线，且不能以数字开头', trigger: 'blur' }
      ]
    }
    
    // 权限分组
    const permissionGroups = [
      {
        key: 'dashboard',
        label: '仪表盘',
        permissions: [
          { value: 'dashboard', label: '查看仪表盘' }
        ]
      },
      {
        key: 'user',
        label: '用户管理',
        permissions: [
          { value: 'user_view', label: '查看用户' },
          { value: 'user_add', label: '添加用户' },
          { value: 'user_edit', label: '编辑用户' },
          { value: 'user_delete', label: '删除用户' },
          { value: 'user_reset_password', label: '重置密码' },
          { value: 'user_export', label: '导出用户' }
        ]
      },
      {
        key: 'exhibitor',
        label: '展商管理',
        permissions: [
          { value: 'exhibitor_view', label: '查看展商' },
          { value: 'exhibitor_add', label: '添加展商' },
          { value: 'exhibitor_edit', label: '编辑展商' },
          { value: 'exhibitor_delete', label: '删除展商' },
          { value: 'exhibitor_approve', label: '审核展商' }
        ]
      },
      {
        key: 'visitor',
        label: '观众管理',
        permissions: [
          { value: 'visitor_view', label: '查看观众' },
          { value: 'visitor_add', label: '添加观众' },
          { value: 'visitor_edit', label: '编辑观众' },
          { value: 'visitor_delete', label: '删除观众' }
        ]
      },
      {
        key: 'news',
        label: '新闻管理',
        permissions: [
          { value: 'news_view', label: '查看新闻' },
          { value: 'news_add', label: '添加新闻' },
          { value: 'news_edit', label: '编辑新闻' },
          { value: 'news_delete', label: '删除新闻' },
          { value: 'news_publish', label: '发布新闻' }
        ]
      },
      {
        key: 'download',
        label: '下载管理',
        permissions: [
          { value: 'download_view', label: '查看下载' },
          { value: 'download_add', label: '添加下载' },
          { value: 'download_edit', label: '编辑下载' },
          { value: 'download_delete', label: '删除下载' }
        ]
      },
      {
        key: 'system',
        label: '系统管理',
        permissions: [
          { value: 'system_setting', label: '系统设置' },
          { value: 'permission_manage', label: '权限管理' },
          { value: 'menu_manage', label: '菜单管理' },
          { value: 'log_view', label: '查看日志' }
        ]
      }
    ]
    
    // 角色数据列表
    const rolesList = ref([])

    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
      if (userInfo.permissions?.includes('all')) return true
      return userInfo.permissions?.includes(permission) || false
    }
    
    // 选择角色
    const selectRole = (role) => {
      selectedRole.value = role
      Object.assign(permissionForm, {
        name: role.roleName,
        description: role.remark,
        permissions: role.permissions || []
      })
    }

    // 加载角色数据
    const loadRoles = async () => {
      loading.value = true
      try {
        const response = await systemApi.getRolePage({
          current: 1,
          size: 100
        })
        if (response.code === '200') {
          rolesList.value = response.data.records || []
        }
      } catch (error) {
        console.error('加载角色数据失败:', error)
        ElMessage.error('加载角色数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 编辑角色
    const editRole = (role) => {
      editingRole.value = role
      Object.assign(roleForm, {
        name: role.roleName,
        description: role.remark,
        code: role.roleCode
      })
      showAddRoleDialog.value = true
    }
    
    // 删除角色
    const deleteRole = async (role) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除角色 "${role.roleName}" 吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await systemApi.deleteRole(role.roleId)
        if (response.code === '200') {
          ElMessage.success('删除成功')
          loadRoles() // 重新加载角色列表
          
          if (selectedRole.value?.roleId === role.roleId) {
            selectedRole.value = null
          }
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除角色失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 保存角色
    const saveRole = async () => {
      saving.value = true
      
      try {
        const roleData = {
          roleName: roleForm.name,
          remark: roleForm.description,
          roleCode: roleForm.code,
          roleType: 'admin',
          roleStatus: '00'
        }
        
        let response
        if (editingRole.value) {
          // 编辑角色
          roleData.roleId = editingRole.value.roleId
          response = await systemApi.updateRole(roleData)
        } else {
          // 添加角色
          response = await systemApi.addRole(roleData)
        }
        
        if (response.code === '200') {
          ElMessage.success(editingRole.value ? '角色更新成功' : '角色添加成功')
          showAddRoleDialog.value = false
          editingRole.value = null
          Object.assign(roleForm, {
            name: '',
            description: '',
            code: ''
          })
          loadRoles() // 重新加载角色列表
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('保存角色失败:', error)
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }
    
    // 保存权限
    const savePermissions = async () => {
      if (!selectedRole.value) {
        ElMessage.warning('请先选择一个角色')
        return
      }
      
      saving.value = true
      
      try {
        // 模拟保存
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 更新角色权限
        const index = rolesList.value.findIndex(r => r.id === selectedRole.value.id)
        if (index > -1) {
          Object.assign(rolesList.value[index], {
            name: permissionForm.name,
            description: permissionForm.description,
            permissions: permissionForm.permissions
          })
        }
        
        ElMessage.success('权限保存成功')
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
    
    // 重置权限
    const resetPermissions = () => {
      if (selectedRole.value) {
        Object.assign(permissionForm, {
          name: selectedRole.value.roleName,
          description: selectedRole.value.remark,
          permissions: [...(selectedRole.value.permissions || [])]
        })
      }
    }
    
    onMounted(async () => {
      await loadRoles()
      // 默认选择第一个角色
      if (rolesList.value.length > 0) {
        selectRole(rolesList.value[0])
      }
    })
    
    return {
      loading,
      saving,
      showAddRoleDialog,
      editingRole,
      selectedRole,
      roleForm,
      permissionForm,
      roleRules,
      permissionGroups,
      rolesList,
      hasPermission,
      selectRole,
      editRole,
      deleteRole,
      saveRole,
      savePermissions,
      resetPermissions
    }
  }
}
</script>

<style scoped>
.admin-permissions {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.role-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.role-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.role-item:hover {
  border-color: #320063;
  box-shadow: 0 2px 8px rgba(50, 0, 99, 0.1);
}

.role-item.active {
  border-color: #320063;
  background: rgba(50, 0, 99, 0.05);
}

.role-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.role-info p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.role-stats {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.role-actions {
  display: flex;
  gap: 10px;
}

.permission-config h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.permission-groups {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.permission-group {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 15px;
}

.permission-group h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 16px;
}

.permission-group .el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.no-selection {
  text-align: center;
  padding: 40px 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .role-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .role-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 